package com.yzkj.cpjxc.business.controller;

import com.yzkj.cpjxc.business.domain.SysUser;
import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.framework.utils.DateTimeUtils;
import com.yzkj.cpjxc.business.framework.utils.JsonUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Controller基类
 */
public class BaseController {


	/**
	 * 导出excel
	 */
	public final static String EXPORT_EXCEL = "exportExcel";
	
	/**
	 * 获取当前页
	 */
	public Integer getCurrentPage(HttpServletRequest request) {
		String currentPage = request.getParameter(Pager.MY_PAGINATION_CURRENT_PAGE);
		int currentPageInt = Integer.parseInt(currentPage == null ? "1" : currentPage);
		return currentPageInt;
	}
	
	/**
	 * 是否导出excel
	 */
	public boolean getExportExcel(HttpServletRequest request) {
		boolean exportExcel = BooleanUtils.toBoolean(request.getParameter(EXPORT_EXCEL));
		return exportExcel;
	}
	
	/**
	 * 记录异常日志信息
	 */
	public void logException(Exception e) {
		StringBuilder sb = new StringBuilder();
		sb.append(e.getMessage()).append("\n");
		for (StackTraceElement ex : e.getStackTrace()) {
			sb.append("\t" + ex.getClassName() + "." + ex.getMethodName() + "(" + ex.getFileName() + ":" + ex.getLineNumber() + ")" ).append("\n");
		}
	}

	/**
	 * list<Object>去除重复项
	 */
	public List<Object> removeDuplicate(List<Object> list) {
		for (int i = 0; i < list.size() - 1; i++) {
			for (int j = list.size() - 1; j > i; j--) {
				if (list.get(j).equals(list.get(i))) {
					list.remove(j);
				}
			}
		}
		return list;
	}

	/**
	 * 获取登录用户
	 */
	public SysUser getLoginUser(HttpServletRequest request) throws Exception {
		return (SysUser)request.getSession().getAttribute(Constants.CURRENT_USER);
	}

	@InitBinder
	public void binder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(DateTimeUtils.sdfyyyyMMdd), true));
		// 如果有格式不为yyyy-MM-dd的，要单独给具体的JavaBean设置
	}

	/**
	 * Ajax调用返回的json数据
	 */
	public String ajax(HttpServletResponse response, Object obj) throws Exception {
		JsonUtils.responseJson(response, obj);
		return null;
	}

	/**
	 * Ajax调用返回的json数据
	 */
	public String ajax(HttpServletResponse response, Object obj, ObjectMapper mapper) throws Exception {
		 JsonUtils.responseJson(response, obj, mapper);
		 return null;
	}
	
	/**
	 * 生成分页json数据
	 */
	public <T> void genPageJson(HttpServletResponse response, Pager<T> pager) throws Exception {
		JsonUtils.responsePageJson(response, pager);
	}
	
	/**
	 * 生成分页json数据
	 */
	public <T> void genPageJson(HttpServletResponse response, Pager<T> pager, String dateFormat) throws Exception {
		JsonUtils.responsePageJson(response, pager, dateFormat);
	}

	/**
	 * 操作完成后页面弹出提示信息，并去到指定的页面
	 */
	public void alertMsg(HttpServletRequest request, HttpServletResponse response, String msg, String redirectUrl) throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");

		StringBuilder sb = new StringBuilder();
		sb.append("<script type='text/javascript'>");
		sb.append("alert(\"" + (StringUtils.isBlank(msg) ? "操作成功" : msg) + "\");");
		if (StringUtils.isBlank(redirectUrl)) {
			sb.append("history.go(-1);");
		} else {
			sb.append("top.location='" + request.getContextPath() + "/" + redirectUrl + "';");
		}
		sb.append("</script>");
		PrintWriter out = response.getWriter();
		out.print(sb.toString());
		out.close();
	}

	/**
	 * <pre>
	 * 处理下载中文文件名时出现的乱码问题
	 * 需要引入apache的 commons-codec-1.4.jar包
	 */
	public String encodeFileName(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
		String agent = request.getHeader("USER-AGENT");

		if (StringUtils.isNotBlank(agent)) {

			// chrome和firefox等
			if (StringUtils.containsIgnoreCase(agent, "Firefox") || StringUtils.containsIgnoreCase(agent, "chrome") || StringUtils.containsIgnoreCase(agent, "Safari")) {
				return "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
			}
			// IE11以下
			if (StringUtils.containsIgnoreCase(agent, "MSIE")) {
				return URLEncoder.encode(fileName, "UTF8");
			}
			// 处理IE11的下载：firefox也包含rv，但是在前面如果是firefox已经处理
			if (StringUtils.containsIgnoreCase(agent, "rv")) {
				return URLEncoder.encode(fileName, "UTF8");
			}
		}
		return fileName;
	}

	/**
	 * <pre>
	 * 下载就是把内容(Object)写到OutputStream里去
	 *  内容指 InputStream ,  byte[] ,  ByteArrayOutputStream
	 */
	public void download(HttpServletRequest request, HttpServletResponse response, Object obj, String fileName) throws Exception {
		response.setContentType("application/x-msdownload;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName(request, fileName));

		if (obj == null) {
			return;
		}

		if (obj instanceof InputStream) {
			try {
				IOUtils.write(IOUtils.toByteArray((InputStream) obj), response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (obj instanceof ByteArrayOutputStream) {
			try {
				IOUtils.write(((ByteArrayOutputStream) obj).toByteArray(), response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (obj instanceof byte[]) {
			try {
				IOUtils.write((byte[]) obj, response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
